package com.waa.gulimall.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.waa.gulimall.common.to.es.SkuEsModel;
import com.waa.gulimall.gulimallsearch.config.GuliMallElasticSearchConfig;
import com.waa.gulimall.gulimallsearch.constant.EsConstant;
import com.waa.gulimall.gulimallsearch.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {
        //保存到es
        //,给es建立索引。product
        final BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModelList) {
            //构造保存请求
            final IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            final String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            //设置要保存的内容，指定数据和类型
            bulkRequest.add(indexRequest);
        }
        final BulkResponse bulkItemResponses = restHighLevelClient.bulk(bulkRequest, GuliMallElasticSearchConfig.COMMON_OPTIONS);
        //TODO 如果批量错误
        final boolean failures = bulkItemResponses.hasFailures();
        final List<String> list = Arrays.stream(bulkItemResponses.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        if (failures)
            log.error("商品上架错误", list);
        return failures;
    }
}
